package com.softwinner.bt.util;

import com.softwinner.bt.service.BtService;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.GetChars;
import android.util.Log;
/**
 * 翼卡联系人存储类
 * @author Administrator
 *
 */
public class EcarConatactsProvider extends ContentProvider {
//	private Database dbHelper;
	private DatabaseHelper mDatabaseHelper;
	private SQLiteDatabase db;
	private static final String LOG_TAG = "EcarConatactsProvider";
	public static final String AUTOHORITY = "com.android.ecar.provider.contacts";
	private static final String TABLE_NAME="phonebook";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/"+TABLE_NAME);
	private static final UriMatcher sMatcher;
	private static final int QUERY_CONTACT_TATABLE = 1;
	private static final int QUERY_CONTACT_TABLE_ID = 2;

	static {
		sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sMatcher.addURI(AUTOHORITY, TABLE_NAME, QUERY_CONTACT_TATABLE);
		sMatcher.addURI(AUTOHORITY, TABLE_NAME+"/#", QUERY_CONTACT_TABLE_ID);
	}

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
	
		return null;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
//		dbHelper = new Database();
		mDatabaseHelper = DatabaseHelper.getDatabaseHelper(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projectionIn, String selection, String[] selectionArgs,
			String sortOrder) {
		// TODO Auto-generated method stub
		/*SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		int match = sMatcher.match(uri);
		switch (match) {
		case QUERY_CONTACT_TATABLE:
			builder.setTables(TABLE_NAME);
			break;
		case QUERY_CONTACT_TABLE_ID:
			builder.setTables(TABLE_NAME);
			builder.appendWhere("_id=");
			builder.appendWhere(uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("unknown uri:" + uri);
		}*/
        Log.i("EcarConatactsProvider", "query");
        //String phoneID = selectionArgs[1];
        String phoneName = selectionArgs[0];
        Cursor ret = null;
        db = mDatabaseHelper.getReadableDatabase();
        if(phoneName!=null){
         //ret = queryContactByCondition(phoneName,phoneID);
        	ret = queryContactByCondition(phoneName);
        }
		return ret;
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		return 0;
	}
	/**
	 * 查询用户根据条件
	 * @param condition 条件
	 * @return
	 */
	public Cursor queryContactByCondition(String condition) {//,String phoneID
		Cursor result = null;
		boolean hasLetter = false;
		if(condition==null){
			condition = "";
		}
		try {
			StringBuilder sb = new StringBuilder();
			
				sb.append("select phonename , phonenumber from  ");
				sb.append(TABLE_NAME);
				/*if(phoneID !=null){
					sb.append(" where phoneID=?");
				}else{
					sb.append(" where 1=1");
				}*/
				sb.append(" where _address='"+BtService.mBtPairAdd+"'");
				
				for (int i = 0; i < condition.length(); i++) {
					String s = condition.substring(i, i + 1);
					//去掉非法字符
					if (s.matches("[\\u4E00-\\u9FA5]") || s.matches("[a-zA-Z]")
                      || s.matches("[0-9]")) {
						sb.append(" and phonename like '%");
						sb.append(s);
						sb.append("%'");
					}
				}
				result = querygetUsersByString(sb.toString());
				return result;
			
		}catch(Exception e){
			BTLog.e(getClass(), "queryContactByCondition error"+e.getLocalizedMessage());
			return null;
		}
	}
	public synchronized Cursor querygetUsersByString(String sql) {
		Cursor cursor  = null ;
		db.beginTransaction();
		if(sql!=null){
			cursor = db.rawQuery(sql,null);
			db.setTransactionSuccessful();
			db.endTransaction();	
		}
		return cursor;
	}
}
